<template>
  <l-layout class="l-tab-page" v-if="!lr_loadPage">
    <template #left>
      <l-panel style="padding-right: 0">
        <template #title>
          {{ $t("分类") }}
          <div class="tree-setting-btn">
            <el-tooltip effect="dark" :content="$t('设置')" placement="top">
              <el-button
                @click="handleSettingClick"
                type="text"
                icon="el-icon-setting"
              ></el-button>
            </el-tooltip>
          </div>
        </template>
        <div class="l-rblock" style="overflow: hidden auto">
          <el-tree
            v-loading="treeLoading" 
            :data="dataItemTree_ImgType"
            :expand-on-click-node="false"
            node-key="value"
            ref="tree"
            :current-node-key="categoryId"
            @node-click="handleNodeClick"
          >
            <span class="lr-tree-node" slot-scope="{ node }">
              {{ node.label }}
            </span>
          </el-tree>
        </div>
      </l-panel>
    </template>
    <l-panel style="padding-left: 0" class="nobg">
      <template #toolLeft>
        <div class="l-panel--item">
          <el-input
            :placeholder="$t('请输入图片名称')"
            @keyup.enter.native="hanleSearch"
            v-model="searchWord"
            size="mini"
          >
            <el-button
              @click="hanleSearch"
              slot="append"
              icon="el-icon-search"
            ></el-button>
          </el-input>
        </div>
      </template>
      <template #toolRight>
        <l-tool-btns :hasAdd="false">
          <el-button-group>
            <l-upload
              :showFileList="false"
              btnText="添加私有图片"
              :uploadCallback="uploadCallback"
              :limit="1000"
              :isSecretLevel="false"
              accept="image/*"
              @success="()=>{loadTablePageData()}"
            ></l-upload>
          </el-button-group>
          <el-button-group>
            <l-upload
              :showFileList="false"
              btnType="success"
              btnText="添加公有图片"
              :uploadCallback="uploadCallbackEX"
              :limit="1000"
              :isSecretLevel="false"
              accept="image/*"
              @success="()=>{loadTablePageData()}"
            ></l-upload>
          </el-button-group>
        </l-tool-btns>
      </template>
      <div
        class="l-rblock"
        style="padding-bottom:48px;background-color:#f0f2f5;"
        v-loading="tableLoading"
      >
        <div class="l-rblock l-overflow-y" >
          <div class="l-v-item l-v-item-w" v-for="item in tableData" :key="item.f_Id">
            <el-image
              fit="contain" lazy
              :src="`${apiUrl}system/annexesfile/${item.f_Id}?token=${token}`"
              :preview-src-list="previewList"
            >
            </el-image>
            <div class="content__main">
              <span class="content__name">{{ item.f_FileName }}</span>
              <div class="content__menulist">
                <div class="content__view">
                  <el-tooltip :content="$t('删除')">
                    <i
                      class="el-icon-delete"
                      @click="handleDelete(item)"
                    ></i>
                  </el-tooltip>
                  <el-tooltip :content="$t('设置')">
                    <i
                      class="el-icon-more"
                      @click="handleSetting(item)"
                    ></i>
                  </el-tooltip>
                </div>
              </div>
            </div>
          </div>
        </div>
        <div class="l-table--pagination" style="border: 0">
          <el-pagination
            layout="total, sizes, prev, pager, next, jumper"
            background
            
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :page-size="tablePageSize"
            :current-page.sync="tableCurrentPage"
            :total="tableTotal"
          >
          </el-pagination>
        </div>
      </div>
    </l-panel>

    <l-drawer
      :title="$t('分类管理')"
      :visible.sync="classifysVisible"
      :showOk="false"
      :showClose="false"
      size="800px"
    >
      <l-dataitem-index classifyCode="ImgType"></l-dataitem-index>
    </l-drawer>

     <l-dialog 
        :title="formTitle"
        :visible.sync="formVisible"
        :height="440"
        @ok="handleSave"
        @close="handleCloseForm"
        @opened="handleOpenedForm"
        >
        <my-form ref="form" ></my-form>       
      </l-dialog>
  </l-layout>
</template>
<script>
import MyForm from './form'
const api = window.$api.system.img
export default {
  components: {
    MyForm
  },
  data() {
    return {
      //查询
      searchWord: "",

      categoryId: "learun_img",
      treeLoading:true,

      tableLoading: false,
      tableData: [],
      tableTotal: 0,
      tablePageSize: 20,
      tableCurrentPage: 1,

      formVisible: false,
      formTitle: "",
      formEditRow:null,

      classifysVisible: false,
    };
  },
  computed: {
    dataItemTree_ImgType() {
      //"f_Id","f_ParentId","f_ItemValue","f_ItemName"
      let data = [{
        f_Id:'learun_img',
        f_ParentId:'0',
        f_ItemValue:'learun_img',
        f_ItemName:this.$t('全部图片'),
        f_EnabledMark:1
      }] 
      data.push(...(this.lr_dataItem["ImgType"] || []))
      return this.lr_dataItemTree(data)
    },
    previewList(){
      return this.tableData.map(t=>`${this.apiUrl}system/annexesfile/${t.f_Id}?token=${this.token}`)
    }
  },
  async created() {
    await this.lr_loadDataItem("ImgType")
    this.treeLoading = false
    this.loadTablePageData()
  },
  methods: {
    handleSettingClick() {
      this.classifysVisible = true;
    },

    handleNodeClick(data) {
      this.categoryId = data.value
      this.loadTablePageData()
    },

    hanleSearch() {
      this.loadTablePageData()
    },

    handleCurrentChange(val) {
      this.tableCurrentPage = val
      this.loadTablePageData(true)
    },
    handleSizeChange(val) {
      this.tablePageSize = val
      this.loadTablePageData(true)
    },
    async loadTablePageData(isNotFirst){
      if(!isNotFirst){
        this.tableCurrentPage = 1
      }
      this.tableLoading = true
      let queryData = {
        rows: this.tablePageSize,
        page: this.tableCurrentPage,
        sidx: "F_CreateDate DESC,F_FileName",
        f_FileName: this.searchWord,
        f_FileType: this.categoryId == 'learun_img'?'':this.categoryId,
      }
      const data = await this.$awaitWraper(api.getPage(queryData))
      if(data){
        this.tableData = data.rows
        this.tableTotal = data.records
      }
      else{
        this.tableData = []
        this.tableTotal = 0
      }
      this.tableLoading = false
    },
    handleDelete(row) {
      this.$confirm(this.$t("此操作将永久删除, 是否继续?"),this.$t("提示"), {
        confirmButtonText: this.$t("确定"),
        cancelButtonText: this.$t("取消"),
        type: "warning",
      }).then(async () => {
        const res = await this.$awaitWraper(api.remove(row.f_Id))
        if(res){
          this.$message({
            type: "success",
            message: this.$t("删除成功!"),
          })
          this.loadTablePageData(this.tableData.length == 1?false:true)
        }
      })
      .catch(() => {
        this.$message({
          type: "info",
          message: this.$t("已取消删除"),
        })
      })
    },
    uploadCallback(data){
      return api.upload(this.categoryId,data)
    },
    uploadCallbackEX(data){
      data.isPublic = 1
      return api.upload(this.categoryId,data)
    },
    handleSetting(row) {
      this.formEditRow = row
      this.showForm(`图片-${row.f_FileName}`);
    },
    async handleSave(showLoading, hideLoading) {
      showLoading('更新数据中...')
      if (await this.$refs.form.validateForm()) {
        const postData = await this.$refs.form.getForm()
        const res = await this.$awaitWraper(api.update(postData.f_Id, postData))
        if (res) {
          this.$message({
            type: 'success',
            message: this.$t('更新成功!')
          })
          this.loadTablePageData(true)
          this.formVisible = false
        }
      }
      hideLoading()
    },

    handleCloseForm() {
      this.$refs.form.resetForm()
    },
    handleOpenedForm(){
      this.$refs.form.setForm(this.formEditRow )
    },
    showForm(text) {
      this.formTitle = text;
      this.formVisible = true;
    },
  },
};
</script>
<style>
.nobg .l-panel--tool {
    background: #fff;
    border: 0;
}
</style>